package com.geezdata.cps.sdk3rd.miya;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.geezdata.cps.base.enums.ErrorCode;
import com.geezdata.cps.base.response.BaseResponse;
import com.geezdata.cps.base.utils.HttpClientUtil;
import com.geezdata.cps.sdk3rd.miya.request.MiyaRequest;
import com.geezdata.cps.sdk3rd.miya.response.MiyaResult;


public class MiyaDefaultClient implements MiyaClient{
    private static final Logger logger = LoggerFactory.getLogger(MiyaDefaultClient.class);

    private String serverUrl;
    
    @SuppressWarnings("unused")
	private String appKey;
    
    @SuppressWarnings("unused")
	private String appScret;
    
    public MiyaDefaultClient(String serverUrl, String appKey, String appScret) {
        super();
        this.serverUrl = serverUrl;
        this.appKey = appKey;
        this.appScret = appScret;
    }

    public <T extends MiyaResult> BaseResponse<T> execute(MiyaRequest<T> request) {
    	if(request == null){
    		return BaseResponse.error(ErrorCode.INVALID_PARAMS.getCode(), ErrorCode.INVALID_PARAMS.getDesc());
        }
    	
        String responseStr = null;
        try {
        	responseStr = HttpClientUtil.post(this.serverUrl, request.getAppParams());
        } catch (Exception e1) {
            logger.error("Http Post is failed",e1); 
            return BaseResponse.error(ErrorCode.HTTP_EXCEPTION.getCode(), e1.getMessage());
        }
        
        JSONObject responseJson = JSONObject.parseObject(responseStr);
        if (responseJson.getInteger("code") != 200) {
        	return BaseResponse.error(ErrorCode.HTTP_EXCEPTION.getCode(), responseJson.getString("msg"));
        }
        
        T miyaResult = null;
        try {
        	miyaResult = request.getResponseClass().newInstance();
        	miyaResult.parseResponseJson(responseJson);
        } catch (Exception e) {
            logger.error("", e);
            return BaseResponse.error(ErrorCode.HTTP_EXCEPTION.getCode(), e.getMessage());
        }
        
		return (BaseResponse<T>) BaseResponse.success(miyaResult); 
    }
}
